<script setup>
import {ref, computed} from 'vue'
import useFileUpload from "@/utiles/common.js";

// 使用您提供的文件上传钩子
const imageUpload = useFileUpload({
  endpoint: 'http://localhost:8081/common/upload',
  extraData: {type: 'invoice'},
  maxSize: 2 * 1024 * 1024,
  allowedTypes: ['image/jpeg', 'image/png', 'image/jpg']
})

// 响应式数据
const fileInput = ref(null)
const uploadedImages = ref([]) // 存储所有上传的图片信息

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)

  if (files.length === 0) return

  // 验证文件并添加到上传队列
  files.forEach(file => {

    // 添加到上传列表，状态为待上传
    uploadedImages.value.push({
      file,
      name: file.name,
      url: URL.createObjectURL(file), // 创建预览URL
      status: 'pending' // pending, uploading, success, error
    })
  })

  // 重置文件输入，允许再次选择相同文件
  event.target.value = ''

  // 自动开始上传
  uploadPendingImages()
}

// 上传所有待处理的图片
const uploadPendingImages = async () => {
  const pendingImages = uploadedImages.value.filter(img => img.status === 'pending')

  for (const image of pendingImages) {
    await uploadSingleImage(image)
  }
}

// 上传单个图片
const uploadSingleImage = async (image) => {
  try {
    // 更新状态为上传中
    image.status = 'uploading'

    // 调用上传函数
    const url = await imageUpload.upload(image.file)

    // 更新状态为成功，并保存服务器返回的URL
    image.status = 'success'
    image.serverUrl = url
    console.log(`图片 "${image.name}" 上传成功:`, url)

  } catch (error) {
    // 更新状态为失败
    image.status = 'error'
    console.error(`图片 "${image.name}" 上传失败:`, error)
    alert(`图片 "${image.name}" 上传失败，请重试`)
  }
}

// 删除图片
const removeImage = (index) => {
  // 释放预览URL的内存
  if (uploadedImages.value[index].url.startsWith('blob:')) {
    URL.revokeObjectURL(uploadedImages.value[index].url)
  }

  uploadedImages.value.splice(index, 1)
}

</script>
<template>
  <div class="image-upload-container">
    <div class="image-list">
      <div
        v-for="(image, index) in uploadedImages"
        :key="index"
        class="image-item"
      >
        <div class="image-preview">
          <img :src="image.url" :alt="`上传图片 ${index + 1}`"/>
          <button class="delete-btn" @click="removeImage(index)" title="删除图片">
            ×
          </button>
        </div>
      </div>
      <div class="upload-area" @click="triggerFileInput">
        <div class="upload-content">
          <i class="upload-icon">+</i>
          <p class="upload-text">点击上传图片</p>
          <p class="upload-hint">支持 JPG、PNG 格式<br>单张图片不超过 2MB</p>
        </div>
        <input
          ref="fileInput"
          type="file"
          accept="image/jpeg, image/png, image/jpg"
          multiple
          @change="handleFileSelect"
          class="file-input"
        />
      </div>
    </div>
  </div>
</template>
<style scoped>
.image-upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;


}


.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  flex: 1;

  .image-item {
    width: 150px;
    overflow: hidden;

    .image-preview {
      position: relative;
      height: 150px;
      overflow: hidden;
    }

    .image-preview img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
    }

    .delete-btn {
      position: absolute;
      top: 5px;
      right: 5px;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background: rgba(255, 0, 0, 0.7);
      color: white;
      border: none;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      line-height: 1;
    }

    .delete-btn:hover {
      background: rgba(255, 0, 0, 0.9);
    }
  }

  /* 右侧上传框 */

  .upload-area {
    width: 150px;
    height: 150px;
    border: 2px dashed #ccc;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background-color: #f9f9f9;
    flex-shrink: 0;


    .upload-content {
      text-align: center;
      pointer-events: none;
    }

    .upload-icon {
      font-size: 36px;
      color: #909399;
      margin-bottom: 8px;
      display: block;
    }

    .upload-text {
      font-size: 14px;
      color: #606266;
      margin-bottom: 5px;
    }

    .upload-hint {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
    }

    .file-input {
      display: none;
    }


  }

  .upload-area:hover {
    border-color: #409eff;
    background-color: #f0f8ff;
  }

}



</style>
